package com.fastloan.core.process;

import com.fastloan.mgt.daily.service.WCustomerManagerDailyService;
import com.fastloan.mgt.processcontrol.base.service.ProcessDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 容器启动之后执行初始化程序(例如刷新缓存等需要初始化功能）.
 *
 * @author johnmyiqn
 */
public class BeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ProcessDispatcher.class);

    @Autowired
    private WCustomerManagerDailyService customerManagerDailyService;

    /**
     * 线程池执行相关定义
     */
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private static final Integer MAX_POOL_SIZE = 300;
    private static Integer current_index = 0;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        /*
            需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
        */
        if (event.getApplicationContext().getParent() == null) {//root application context 没有parent，他就是老大.
            //执行初始化任务(spring启动之后)
            startUpTask();
        }
    }

    /**
     * 按照线程池执行定时任务
     */
    private void startUpTask(){
        try{
            //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            addTask(() -> {
                Date beforeDateMenu = new Date();
                //微信日报初始化
                customerManagerDailyService.batchInsertDailyCommit();
                getTaskTime(beforeDateMenu,"微信日报初始化");
            },"微信日报初始化");

        } catch (Exception e) {
            logger.error("容器启动后指定代码异常");
            e.printStackTrace();
        }
    }

    /**
     * 线程池添加任务
     * @param task 线程任务
     */
    private void addTask(Runnable task,String taskDesc){
        logger.info("添加执行任务:"+taskDesc);
        if(current_index < MAX_POOL_SIZE){
            //添加任务
            executorService.submit(task);
            current_index++;
        }else{
            logger.info("启动定时任务添加失败","数量限制"+MAX_POOL_SIZE);
        }
    }

    /**
     * 线程池添加任务
     * @param date 线程任务执行开始时间
     * @param taskDesc 线程信息描述
     */
    private void getTaskTime(Date date,String taskDesc){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info(taskDesc+"任务开始时间："+simpleDateFormat.format(date));
        Date currentTime = new Date();
        Long time = (currentTime.getTime() - date.getTime());
        logger.info(taskDesc+"任务结束时间："+simpleDateFormat.format(currentTime));
        logger.info(taskDesc+"任务运行时间："+time+"毫秒");
    }
}
